package cn.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class loginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");

		/*
		 * 校验验证码
		 * 1.获取输入内容
		 * 2.获取session中内容
		 * 3.比较内容
		 * 4.若相同向下走，若不同则保存错误信息到request域中。
		 */
		String vcname=request.getParameter("vcname");
		String vsname=(String) request.getSession().getAttribute("vcode");
		
		//一旦比较失败则不再运行
		if(!vcname.equalsIgnoreCase(vsname)){//忽略大小写的比较
			request.setAttribute("mes", "验证码错误！");
			request.getRequestDispatcher("/CookieSession/Login.jsp").forward(request, response);
			return;
		}
		
		//获取表单数据		
		
		String name=request.getParameter("username");
		String password=request.getParameter("password");
		
		Cookie c=new Cookie("username", name);//创建Cookie
		c.setMaxAge(60*60*24);//设置Cookie命长为一天
		response.addCookie(c);
	
		if("hyh".equals(name)&&"123".equals(password)){
			
			HttpSession s=request.getSession();
			s.setAttribute("username", name);//报存用户名
			response.sendRedirect("/jspdemo/CookieSession/succeed.jsp");//Session中的东西不会因转发而丢掉，所可以重定向
			
		}else{
			request.setAttribute("mes", "用户名密码错误！");
			request.getRequestDispatcher("/CookieSession/Login.jsp").forward(request, response);
		}
	}

}